<!-- 计数器组件 -->
<template>
  <div class="counter">
    <div
      class="counter-sub"
      :style="num <= minNum ? 'color: #ccc;' : ''"
      @click="sub"
    >
      -
    </div>
    <div class="counter-num">{{ num }}</div>
    <div
      class="counter-add"
      :style="num >= maxNum ? 'color: #ccc;' : ''"
      @click="add"
    >
      +
    </div>
  </div>
</template>

<script>
export default {
  name: "",
  props: {
    defaultNum: {
      type: Number,
      default: 0
    },
    minNum: {
      type: Number,
      default: -Infinity
    },
    maxNum: {
      type: Number,
      default: Infinity
    }
  },
  data() {
    return {
      num: 0
    };
  },
  created() {
    if (this.defaultNum < this.minNum || this.defaultNum > this.maxNum) {
      this.num = this.minNum;
    } else {
      this.num = this.defaultNum;
    }
  },
  components: {},
  methods: {
    add() {
      let t = this.num + 1;
      t <= this.maxNum ? (this.num = t) : (this.num = this.maxNum);
    },
    sub() {
      let t = this.num - 1;
      t >= this.minNum ? (this.num = t) : (this.num = this.minNum);
    },
    event(num) {
      this.$emit("numChange", num);
    }
  },
  watch: {
    minNum(val) {
      if (this.defaultNum < this.minNum || this.defaultNum > this.maxNum) {
        this.num = this.minNum;
      } else {
        this.num = this.defaultNum;
      }
    },
    maxNum(val) {
      if (this.defaultNum < this.minNum || this.defaultNum > this.maxNum) {
        this.num = this.minNum;
      } else {
        this.num = this.defaultNum;
      }
    },
    defaultNum(val) {
      if (this.defaultNum < this.minNum || this.defaultNum > this.maxNum) {
        this.num = this.minNum;
      } else {
        this.num = this.defaultNum;
      }
    },
    num(val) {
      this.event(val);
    }
  }
};
</script>

<style scoped>
.counter {
  width: 100%;
  height: 100%;
  background: #fff;
  border: 1px solid #ccc;
  border-radius: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.counter-sub,
.counter-num,
.counter-add {
  height: 100%;
  flex: 1;
  padding: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.counter-sub,
.counter-add {
  font-size: 20px;
}
.counter-num {
  color: #333;
  font-size: 14px;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
}
</style>
